import { GIcon, GModalButton } from 'geminis-react';
import { BpmnModeler } from '@/pages/workflow/model/components/modeler/modeler';
import { useCallback, useState } from 'react';
import { ModelerService } from '@/pages/workflow/model/components/modeler/ModelerService';
import { message } from 'antd';
import { request } from '@umijs/max';

export const ModelEdit = (props: any) => {
  const [modelerService] = useState(new ModelerService());

  const save = useCallback((): Promise<any> => {
    return modelerService.modeller.saveXML().then(({ xml }: any) => {
      return request('/api/workflow/model?category=' + props.getCategoryId(), {
        method: 'put',
        data: xml,
        headers: {
          'Content-Type': 'text/plain',
        },
      })
        .then(() => {
          message.success('成功');
          props.onSaved?.();
          clean();
        }).catch((err: any) => {
          message.error('保存流程错误');
          throw err;
        });
    });
  }, []);

  const clean = useCallback(() => {
    modelerService.clean();
  }, []);

  return (
    <GModalButton
      text={props.text}
      button={{
        icon: <GIcon type={props.icon} />,
        type: props.type,
      }}
      modal={{
        width: '90vw',
        bodyStyle: {
          overflow: 'auto',
          height: '70vh',
          padding: 0,
        },
      }}
      onOk={save}
      onCancel={clean}
    >
      <BpmnModeler
        modelerService={modelerService}
        url={
          props.modelId
            ? '/api/workflow/model/' + props.modelId + '/bpmn'
            : '/workflow-pc/schema/model/defaultModel.xml'
        }
      />
    </GModalButton>
  );
};
